package com.o2o.service.impl;

import com.o2o.dao.ShopDao;
import com.o2o.dto.ImageHolder;
import com.o2o.dto.ShopExecution;
import com.o2o.entity.Shop;
import com.o2o.enums.ShopStateEnum;
import com.o2o.exceptions.ShopOperationException;
import com.o2o.service.ShopService;
import com.o2o.utils.FileUtil;
import com.o2o.utils.ImageUtil;
import com.o2o.utils.PageCalculator;
import com.o2o.utils.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.Date;
import java.util.List;

/**
 * package_name:com.o2o.service.impl
 * Author:徐亚远
 * Date:2019/11/28 9:54
 * 项目名:o2o
 * Desription:
 **/
@Service
public class ShopServiceImpl implements ShopService {
    private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);
    @Autowired
    private ShopDao shopDao;

    /*
     * @param shopCondition
     * @param pageIndex
     * @param pageSize
     * @return ShopExcution
     * 根据shopCondition分页查询数据
     * */
    @Override
    public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex,pageSize );
        List<Shop> shopList = shopDao.queryShopList(shopCondition, pageIndex,pageSize );
        int count = shopDao.queryShopCount(shopCondition);
        ShopExecution se = new ShopExecution();
        if (shopList != null){
                se.setShopList(shopList);
                se.setCount(count);
        }else {
            se.setState(ShopStateEnum.INNER_ERROR.getState());
        }
        return se;
    }

    /*
     * @param shop
     * @return int
     * 添加店铺信息
     * */
    @Override
    public int shopInsert(Shop shop) {
        int sh = shopDao.insertShop(shop);
        System.out.println("sh的值为:" + sh);
        return sh;
    }

    /*
     *更新店铺信息,包括对图片的处理
     * @param shop
     * @param shopImg
     * @return
     * @throws ShopOperationException
     * */
    @Override
    public ShopExecution modifyShop(Shop shop, ImageHolder thumbnail) throws
            ShopOperationException {
        if (shop == null || shop.getShopId() == null) {
            return new ShopExecution(ShopStateEnum.NUL_SHOP);
        } else {
            //1:判断是否需要处理图片
            try {
                if (thumbnail.getImage() != null && thumbnail.getImageName() != null && !"".equals(thumbnail.getImageName())) {
                    Shop tempShop = shopDao.queryShopId(shop.getShopId());
                    if (tempShop.getShopImg() != null) {
                        System.out.println("执行这个判断了吗tempShop.getShopImg()!=null");
                        ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                    }
                    addShopImg(shop, thumbnail);
                    System.out.println("添加图片执行了吗");
                }
                //2:更新店铺信息
                shop.setLastEditTime(new Date());
                int effectedNum = shopDao.updateShop(shop);
                if (effectedNum <= 0) {
                    return new ShopExecution(ShopStateEnum.INNER_ERROR);
                } else {
                    shop = shopDao.queryShopId(shop.getShopId());
                    return new ShopExecution(ShopStateEnum.SUCCESS, shop);
                }
            } catch (Exception e) {
                throw new ShopOperationException("modifyShop error:" + e.getMessage());
            }
        }
    }

    /*
     * @param shopId
     * @return Shop
     * 通过shopId查询店铺信息
     * */
    @Override
    public Shop queryByShopId(Long shopId) {
        return shopDao.queryShopId(shopId);
    }

    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, ImageHolder thumbnail) {
        // 非空判断 (这里先判断shop是否为空，严格意义上讲shop中的are的属性也需要判断)
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        // 关键步骤1. 设置基本信息，插入tb_shop
        // 初始状态： 审核中
        shop.setEnableStatus(0);
        shop.setCreateTime(new Date());
        shop.setLastEditTime(new Date());
        int effectedNum = shopDao.insertShop(shop);
        if (effectedNum <= 0) {
            throw new ShopOperationException("店铺创建失败");
        } else {
            // 关键步骤2. 添加成功,则继续处理文件,获取shopid,用于创建图片存放的目录
            if (thumbnail.getImage() != null) {
                try {
                    // 需要根据shopId来创建目录,所以也需要shop这个入参
                    System.out.println("到这里了吗");
                    addShopImg(shop, thumbnail);
                    System.out.println("是这个addShopImg方法报错了吗");
                } catch (Exception e) {
                    System.out.println("此处报错品牌");
                    logger.error("addShopImg error {} ", e.toString());
                    throw new ShopOperationException("addShopImg error:" + e.getMessage());
                }
                // 关键步骤3. 更新tb_shop中 shop_img字段
                effectedNum = shopDao.updateShop(shop);
                if (effectedNum <= 0) {
                    logger.error("updateShop error {} ", "更新店铺失败");
                    throw new ShopOperationException("updateShop error");
                }
            }
        }
        // 返回店铺的状态：审核中，以及店铺信息
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }

    /*删除用户通过shop_id*/
    @Override
    public int deleteShop(Long shop_id) {
        return shopDao.deleteShop(shop_id);
    }

    private void addShopImg(Shop shop, ImageHolder thumbnail) {
        String imgPath = FileUtil.getShopImagePath(shop.getShopId());
        // 生成图片的水印图
        String relativeAddr = ImageUtil.generateThumbnails( imgPath,thumbnail);
        // 将相对路径设置个shop,用于更新数据库
        shop.setShopImg(relativeAddr);
    }

    /*controller 层测试*/
    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, CommonsMultipartFile shopImg) {
        //控制判断
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NUL_SHOP);
        }
        try {
            /*给店铺信息赋初始值*/
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            /*添加店铺信息*/
            int effectedNum = shopDao.insertShop(shop);
            if (effectedNum <= 0) {
                throw new ShopOperationException("店铺创建失败");
            } else {
                if (shopImg != null) {
                    /*存储图片*/
                    try {
                        addShop(shop, shopImg);
                    } catch (Exception e) {
                        throw new ShopOperationException("addShopImg error:" + e.getMessage());
                    }
                    /*更新店铺的图片地址*/
                    effectedNum = shopDao.updateShop(shop);
                    if (effectedNum <= 0) {
                        throw new ShopOperationException("更新图片地址失败");
                    }
                }
            }
        } catch (Exception e) {
            throw new ShopOperationException("addShop error" + e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }

    private void addShopImg(Shop shop, CommonsMultipartFile shopImg) {
        /*获取shop图片目录的相对值路径*/
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        System.out.println("dest的路径为:ShopServiceImpl测试:" + dest);
        String shopImgAddr = ImageUtil.generateThumbnail(shopImg, dest);
        System.out.println("shopImgAddr的路径为:ShopServiceImpl测试:");
        shop.setShopImg(shopImgAddr);
    }

/*
    @Override
    @Transactional
    public ShopExecution addShop(File shopImg, Shop shop) {
        // 非空判断 (这里先判断shop是否为空，严格意义上讲shop中的are的属性也需要判断)
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        // 关键步骤1. 设置基本信息，插入shop
        // 初始状态： 审核中
        shop.setEnableStatus(0);
        shop.setCreateTime(new Date());
        shop.setLastEditTime(new Date());
        int effectedNum = shopDao.insertShop(shop);
        if (effectedNum <= 0) {
            throw new ShopOperationException("店铺创建失败");
        } else {
            // 关键步骤2. 添加成功,则继续处理文件,获取shopid,用于创建图片存放的目录
            if (shopImg != null) {
                try {
                    // 需要根据shopId来创建目录,所以也需要shop这个入参
                    addShopImg(shop, shopImg);
                } catch (Exception e) {
                    logger.error("addShopImg error {} ", e.toString());
                    throw new ShopOperationException("addShopImg error:" + e.getMessage());
                }
                // 关键步骤3. 更新tb_shop中 shop_img字段
                effectedNum = shopDao.updateShop(shop);
                if (effectedNum <= 0) {
                    logger.error("updateShop error {} ", "更新店铺失败");
                    throw new ShopOperationException("updateShop error");
                }
            }
        }
        // 返回店铺的状态：审核中，以及店铺信息
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }
    private void addShopImg(Shop shop, File shopImg) {
        String imgPath = FileUtil.getShopImagePath(shop.getShopId());
        // 生成图片的水印图
        String relativeAddr = ImageUtil.generateThumbnails(shopImg, imgPath);
        // 将相对路径设置个shop,用于更新数据库
        shop.setShopImg(relativeAddr);
    }*/
}
